<template>
  <layout>
    <template slot="title">
      <span style="margin-right: 10px">农户信息列表（共{{total}}户）</span>
      <a-button
        type="primary"
        icon="plus"
        style="margin-right: 10px;margin-left: 20px;"
        :auth="{
          key: ['member.add', currentAreaId.length === 14],
          relate: 'and'
        }"
        @click="handlerTableAdd"
      >新增农户</a-button>
       <a-popconfirm
          title="您确认要同步上一年数据到本年度?"
          ok-text="确认"
          cancel-text="取消"
          @confirm="handlerSyncData"
        >
          <a-button
          type="primary"
          style="margin-right: 20px;"
          :loading="syncLoading"
          :auth="{
            keys: ['member.sync-last-year', currentAreaId.length === 6],
            relate: 'and'
          }"
        >同步上一年数据</a-button>
      </a-popconfirm>

      <a-button-group>
        <a-button
          type="primary"
          icon="cloud-upload"
          @click="() => handlerUploadExecl()"
        >
          从单机版农户信息表导入
        </a-button>
        <a-button
          icon="download"
          style="margin-right: 20px;"
          @click="handlerDownload($downloadUrl)"
        >
        下载模板
          <!-- <a :href="$downloadUrl" target="_blank">下载模板</a> -->
        </a-button>
      </a-button-group>

      <a-button-group>
        <a-button
          type="primary"
          icon="cloud-upload"
          @click="() => handlerUploadExecl(false)"
        >
          从单机版补贴对象表导入
        </a-button>
        <a-button
          type="default"
          icon="download"
          @click="handlerDownload($downloadGrainTemplate)"
          style="margin-right: 20px;"
        >
        下载模板
          <!-- <a :href="$downloadUrl" target="_blank">下载模板</a> -->
        </a-button>
      </a-button-group>
        <a-button
          type="dashed"
          icon="question-circle"
          @click="handlerHelper"
        >
          帮助
        </a-button>
        <!-- <a-radio-group v-model="currentRenderMode">
          <a-radio-button value="1" icon="bars">
            明细
          </a-radio-button>
          <a-radio-button value="2">
            汇总
          </a-radio-button>
        </a-radio-group> -->
    </template>

    <!-- 顶部操作 -->
    <section slot="search">
      <custom-form
        ref="search-form"
        class="search-form"
        v-model="tableSearch"
        layout="inline"
        mode="search"
        :FormList="searchColumns"
      >
        <a-button
          class="action-button"
          type="primary"
          @click="search()"
        >搜索</a-button>

        <!-- <a-button
          class="action-button"
          type="primary"
          @click="search()"
        >重复数据查验</a-button> -->
      </custom-form>
      <!-- <a-input placeholder="产品名称或者编号" v-model="tableSearch.searchKey" allowClear style="width: 200px;" /> -->
    </section>

    <!-- 产品列表 -->
    <a-table
      :dataSource="tableData"
      :columns="tableColumns"
      :rowKey="record => record.usr_id"
      :pagination="false"
      :loading="tableLoading"
      size="small"
      :customRow="(record) => {
        return {
          on: {
            click: () => {
              handlerFamily(record)
            }
          }
        }
      }"
      :scroll="{
        x: '100%',
        y: tableClientHeight - 100
      }"
      bordered
    >
      <template
        slot="family_id"
        slot-scope="row"
      >
        <!-- <a-tooltip v-if="row.member_oid">
          <template slot="title">
            旧版编号：{{row.member_oid}}
          </template>
          <a>{{row.family_id}}</a>
        </a-tooltip>
        <span v-else>{{row.family_id}}</span> -->
        <a>{{row.family_id}}</a>
      </template>
      <template
        slot="role"
        slot-scope="row"
      >
        {{getLabel(row.role, [], 'role')}}
      </template>
      <template
        slot="member_sex"
        slot-scope="row"
      >
        {{getLabel(row.member_sex, [], 'member_sex')}}
      </template>
      <template
        slot="member_bank_code"
        slot-scope="row"
      >
        {{getLabel(row.member_bank_code, [], 'member_bank_code')}}
      </template>
      <!-- 按钮区 -->
      <template
        slot="action"
        slot-scope="row"
      >
        <a-button
          class="action-button"
          type="link"
          size="small"
          auth="member.edit"
          @click="handleTableEdit(row)"
        >编辑</a-button>
        <a-popconfirm
          title="您确认要删除该条数据?"
          ok-text="确认"
          cancel-text="取消"
          @confirm="tableDel(row)"
        >
          <a-button
            class="action-button"
            type="link"
            auth="member.delete"
            size="small"
          >删除</a-button>
        </a-popconfirm>
        <a-button
          class="action-button"
          type="link"
          size="small"
          auth="member.list"
          @click="handlerFamily(row)"
        >管理家庭成员</a-button>
        <a-button
          class="action-button"
          type="link"
          size="small"
          auth="member.grain"
          @click="handlerGrain(row)"
        >耕地与种粮信息</a-button>
        <!-- <a-button
          class="action-button"
          type="primary"
          size="small"
          @click="handleTableEdit(row)"
        >项目管理</a-button> -->
      </template>
    </a-table>

    <!-- 产品列表分页器 -->
    <a-pagination
      slot="paging"
      :pageSizeOptions="pageSizes"
      :total="total"
      :show-total="showTotal"
      showSizeChanger
      :pageSize="pageSize"
      v-model="currentPage"
      @showSizeChange="changePageSize"
      @change="changePage"
    >
    </a-pagination>

    <!-- 编辑产品数据 -->
    <a-modal
      :visible="visible"
      :title="visibleTitle"
      centered
      :confirmLoading="visibleLoading"
      @cancel="visible = false"
      @ok="handleSubmit"
    >
      <custom-form
        ref="custom-form"
        class="custom-form"
        v-model="currentRow"
        :FormList="formColumns"
        :mode="formMode"
        v-bind="formItemLayout"
        layout="horizontal"
      ></custom-form>
      <!-- <section slot="footer"> -->
      <!-- <a-button
        type="primary"
        @click="handleSubmit"
      >提交</a-button> -->
      <!-- </section> -->
    </a-modal>

    <MemberImport ref="MemberImport" />

  </layout>
</template>

<script lang="ts">
import { Mixins, Component, Watch, Vue, Prop } from 'vue-property-decorator'
import { State, Mutation, Getter, namespace } from 'vuex-class'
import { CreateElement } from 'vue'
import EventsMixin from '@/mixin/events'
import { TableMixin, AuthMixin } from '@/mixin'

import { TableLayout } from '@/layouts'
import CustomForm from '@/components/src/Form'
import { userServices, IAdmin } from '@/common/services'
import { famerServices, IMember } from '@/common/services/famer'
import { commonServices } from '@/common/services/common'
import { memberRole } from '@/common/enum'
import MemberImport from './MemberImport.vue'

import { appModule } from '@/store/modules/app'
import { message } from 'ant-design-vue'

@Component({
  components: {
    Layout: TableLayout,
    CustomForm,
    MemberImport
  }
})
export default class AdminList extends Mixins(
  EventsMixin,
  TableMixin,
  AuthMixin
) {
  @Prop({
    type: String
  })
  public currentAreaId!: string

  @Prop({
    type: String
  })
  public currentAreaName!: string

  // 当前列表渲染模式
  public currentRenderMode = '1'

  get isLargeScreen() {
    return appModule.isLargeScreen
  }

  public commonParams = {
    s_a_id: ''
  }

  // 产品列表搜索条件
  public tableSearch = {
    role: '1'
  }

  // 产品列表表格信息
  public columns: ITable.IColumn[] = [
    {
      title: '农户编号',
      key: 'family_id',
      scopedSlots: { customRender: 'family_id' },
      width: 160,
      form: {
        type: 'a-input',
        placeholder: '输入农户编号',
        disabled: ['add', 'edit'],
        isShowFrom: false,
        // renderMode: ['edit', 'search'],
        isShowQuery: true
      }
    },

    // 表单专用
    {
      title: '农户编号',
      key: 'family_id',
      width: 160,
      form: {
        type: 'a-input',
        placeholder: '--自动生成--',
        disabled: ['add', 'edit'],
        // renderMode: ['edit', 'search'],
        isShowQuery: false,
        isShowFrom: true,
        isShowList: false
      }
    },
    {
      title: '户口本编号',
      dataIndex: 'family_book_id',
      key: 'family_book_id',
      width: 100,
      form: {
        type: 'a-input',
        placeholder: '输入户口本编号'
      }
    },
    {
      title: '家庭住址',
      dataIndex: 'member_addr',
      key: 'member_addr',
      width: 240,
      form: {
        type: 'a-textarea',
        placeholder: '输入家庭住址'
      }
    },
    {
      title: '人口数',
      dataIndex: 'member_num',
      key: 'member_num',
      width: 60
    },

    // {
    //   title: '行政地区编号',
    //   dataIndex: 's_a_id',
    //   key: 's_a_id',
    //   form: {
    //     type: 'a-input',
    //     placeholder: '输入行政地区编号',
    //     disabled: true
    //   }
    // },
    {
      title: '户主姓名',
      dataIndex: 'member_nam',
      key: 'member_nam',
      width: 80,
      form: {
        type: 'a-input',
        placeholder: '输入户主姓名',
        isShowQuery: true,
        validate: '*'
      }
    },
    {
      title: '性别',
      key: 'member_sex',
      width: 50,
      scopedSlots: { customRender: 'member_sex' },
      form: {
        type: 'a-radio-group',
        placeholder: '选择性别',
        isShowQuery: false,
        defaultValue: 1,
        dict: [
          {
            label: '男',
            value: '1'
          },
          {
            label: '女',
            value: '2'
          }
        ]
      }
    },
    {
      title: '身份证号',
      dataIndex: 'member_sfz',
      key: 'member_sfz',
      width: 160,
      form: {
        type: 'a-input',
        placeholder: '输入户主身份证号',
        isShowQuery: true,
        // validate: '*'
      }
    },
    {
      title: '手机号',
      dataIndex: 'member_tel',
      key: 'member_tel',
      width: 110,
      form: {
        type: 'a-input',
        placeholder: '输入户主手机号',
        isShowQuery: true,
        // validate: '*'
      }
    },
    // {
    //   title: '与户主关系',
    //   key: 'role',
    //   scopedSlots: { customRender: 'role' },
    //   form: {
    //     type: 'a-select',
    //     placeholder: '选择与户主关系',
    //     disabled: true,
    //     dict: memberRole
    //   }
    // },
    {
      title: '银行卡号',
      dataIndex: 'member_bank_num',
      key: 'member_bank_num',
      width: 180,
      form: {
        type: 'a-input',
        placeholder: '输入户主银行卡号',
        isShowQuery: true
      }
    },
    {
      title: '开户银行',
      key: 'member_bank_code',
      width: 150,
      scopedSlots: { customRender: 'member_bank_code' },
      form: {
        type: 'a-auto-complete',
        placeholder: '选择/输入 开户银行名称',
        showSearch: true,
        dataSource: []
      }
    },
    {
      title: '备注',
      dataIndex: 'readme',
      key: 'readme',
      width: this.isLargeScreen ? 'auto' : 300,
      form: {
        type: 'a-textarea',
        placeholder: '输入备注'
      }
    },
    {
      title: '操作',
      key: 'action',
      width: 300,
      fixed: 'right',
      scopedSlots: { customRender: 'action' }
    }
  ]

  public tableApi = {
    list: famerServices.getMemberList,
    add: famerServices.updateMember,
    edit: famerServices.updateMember,
    del: famerServices.deleteMember
    // imageUpload: 'uploadStoreImage',
    // imageRemove: 'delStoreImage'
  }

  @Watch('currentAreaId', { immediate: true })
  public handlerCurrentAreaIdChange() {
    this.commonParams.s_a_id = this.currentAreaId
    // 重置家庭成员列表
    this.events.trigger('select-houseHolder', {})
    this.getData()
  }

  public mounted() {
    this.getBankTypes()
    this.getData()

    // 监听户主更新事件刷新列表
    this.events.listen('update-holder', () => {
      this.getData()
    })
    this.$on('hook:beforeDesotry', () => {
      this.events.remove('update-holder')
    })
  }

  public handlerHelper() {
    this.events.trigger('show-helper')
  }

  public async getData() {
    const res = await this.getTableList()
  }

  public handlerGrain(row: IMember) {
    this.$router.push({
      path: '/member/grain',
      query: { id: row.family_id, s_a_id: row.s_a_id }
    })
  }

  public getBankTypes() {
    commonServices.getBankType().then(res => {
      const dict = []
      this.changeDict(
        'member_bank_code',
        Object.keys(res.data).map(key => res.data[key]),
        'dataSource'
      )
    })
  }

  public handlerTableAdd() {
    this.tableAdd()
    this.$nextTick(() => {
      this.currentRow = Object.assign(
        {},
        { s_a_id: this.currentAreaId, member_sex: '1', member_addr: this.currentAreaName }
      )
      this.visibleTitle = '添加农户'
    })
  }

  public handlerFamily(row: IMember) {
    this.events.trigger('select-houseHolder', row)
  }

  // 编辑前数据预处理
  public async handleTableEdit(row: any) {
    this.tableEdit(Object.assign({}, row))
  }

  public handlerUploadExecl(isMember: boolean = true) {
    this.$refs.MemberImport.handlerUploadExecl(isMember)
  }

  // 下载
  public handlerDownload(link: string) {
    const a = document.createElement('a')
    a.href = link
    a.target = '_blank'
    a.click();
  }

  // 同步上一年数据
  public syncLoading = false
  public handlerSyncData() {
    const loading = message.loading({
      content: '数据正在同步中。。。请稍后'
    })
    this.syncLoading = true
    famerServices.syncLastYearData({
      s_a_id: this.currentAreaId
    }).then(_ => {
      this.$message.success('同步成功')
    }).finally(() => {
      loading()
      this.syncLoading = false
    })
  }
}
</script>

<style scoped lang="less">
.action-button {
  margin: 0px 10px 0px 10px;
}
.form-item-class {
  margin-bottom: 0px;
}
.img-box {
  width: 100px;
  height: 100px;
  margin: 10px;
}
.item-blue {
  color: #1989fa;
}

.search-form {
  /deep/ input {
    width: 140px;
  }
}
.search-button-group {
  display: flex;
  justify-content: space-between;
  align-items: center;
  // width: 400px;
}
</style>
